package com.showtao.common.dto.widget;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

@SuppressWarnings("serial")
public class DataTablesRequestDto implements Serializable {

    private int draw;
    private int start;
    private int length;
    private List<DataTablesRequestColumnDto> columns;
    private List<DataTablesRequestOrderDto> order;
    private DataTablesRequestSearchDto search;

    public int getDraw() {
        return draw;
    }

    public void setDraw(int draw) {
        this.draw = draw;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public List<DataTablesRequestColumnDto> getColumns() {
        return columns;
    }

    public void setColumns(List<DataTablesRequestColumnDto> columns) {
        this.columns = columns;
    }

    public List<DataTablesRequestOrderDto> getOrder() {
        return order;
    }

    public void setOrder(List<DataTablesRequestOrderDto> order) {
        this.order = order;
    }

    public DataTablesRequestSearchDto getSearch() {
        return search;
    }

    public void setSearch(DataTablesRequestSearchDto search) {
        this.search = search;
    }

    public Pageable toPagable() {

        Sort sort = null;
        if (!CollectionUtils.isEmpty(this.getOrder()) && 
                !CollectionUtils.isEmpty(this.getColumns())) {
            List<Order> orders = new ArrayList<Order>();
            List<DataTablesRequestColumnDto> cols = this.getColumns();
            for (DataTablesRequestOrderDto o : this.getOrder()) {
                if (cols.size() >= o.getColumn()) {
                    DataTablesRequestColumnDto col = cols.get(o.getColumn());
                    String orderProperty = col.getData();
                    Order order = new Order(Direction.fromStringOrNull(o.getDir()),orderProperty);
                    orders.add(order);
                }
            }
            sort = new Sort(orders);
        }

        return new PageRequest(length !=0 ? Double.valueOf(
                Math.ceil(start / length)).intValue() : 0, length !=  0? length: 1, sort);
    }
}
